package com.locationtracker.plus.app.network

import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.ThreadUtils.runOnUiThread
import com.locationtracker.plus.app.eventViewModel
import com.locationtracker.plus.app.util.CacheUtil
import com.locationtracker.plus.data.model.bean.ApiResponse
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import java.io.IOException

/**
 * 作者　: hegaojian
 * 时间　: 2022/1/13
 * 描述　: token过期拦截器
 */
class TokenOutInterceptor : Interceptor {

    @kotlin.jvm.Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val response = chain.proceed(chain.request())
        return if (response.body != null && response.body!!.contentType() != null) {
            val mediaType = response.body!!.contentType()
            val string = response.body!!.string()
            val responseBody = string.toResponseBody(mediaType)
            val apiResponse = GsonUtils.fromJson(string, ApiResponse::class.java)
            if (apiResponse.getResponseCode() == 401) {
                CacheUtil.setToken(null)
                //如果是普通的activity话 可以直接跳转，如果是navigation中的fragment，可以发送通知跳转
                runOnUiThread {
                    eventViewModel.loginEvent.value = false
                }
            }
            response.newBuilder().body(responseBody).build()
        } else {
            response
        }
    }
}